//创建地图
var map, district, polygons = [], citycode;
var citySelect = document.getElementById('city');
var districtSelect = document.getElementById('district');
var areaSelect = document.getElementById('street');

map = new AMap.Map('container', {
    resizeEnable: true,
    center: [108.947001, 34.259458],
    zoom: 4
});

map.plugin(["AMap.ToolBar"], function() {
    map.addControl(new AMap.ToolBar());
});

//行政区划查询
var opts = {
    subdistrict: 1,   //返回下一级行政区
    showbiz: false  //最后一级返回街道信息
};

district = new AMap.DistrictSearch(opts);
district.search('中国', function (status, result) {
    if (status == 'complete') {
        getData(result.districtList[0]);
    }
});

function getData(data, level) {
    var bounds = data.boundaries;
    if (bounds) {
        for (var i = 0, l = bounds.length; i < l; i++) {
            var polygon = new AMap.Polygon({
                map: map,
                strokeWeight: 1,
                strokeColor: '#CC66CC',
                fillColor: '#ED1C24',
                fillOpacity: 0.5,
                path: bounds[i]
            });
            polygons.push(polygon);
        }
        map.setFitView();//地图自适应
    }

    //清空下一级别的下拉列表
    if (level === 'province') {
        citySelect.innerHTML = '';
        districtSelect.innerHTML = '';
        areaSelect.innerHTML = '';
    } else if (level === 'city') {
        districtSelect.innerHTML = '';
        areaSelect.innerHTML = '';
    } else if (level === 'district') {
        areaSelect.innerHTML = '';
    }

    var subList = data.districtList;
    if (subList) {
        var contentSub = new Option('--请选择--');
        var curlevel = subList[0].level;
        var curList = document.querySelector('#' + curlevel);
        curList.add(contentSub);
        for (var i = 0, l = subList.length; i < l; i++) {
            var name = subList[i].name;
            var levelSub = subList[i].level;
            var cityCode = subList[i].citycode;
            contentSub = new Option(name);
            contentSub.setAttribute("value", levelSub);
            contentSub.center = subList[i].center;
            contentSub.adcode = subList[i].adcode;
            curList.add(contentSub);
        }
    }

}

function search(obj) {
    //清除地图上所有覆盖物
    for (var i = 0, l = polygons.length; i < l; i++) {
        polygons[i].setMap(null);
    }
    var option = obj[obj.options.selectedIndex];
    var keyword = option.text; //关键字
    var adcode = option.adcode;
    district.setLevel(option.value); //行政区级别
    district.setExtensions('all');
    //行政区查询
    //按照adcode进行查询可以保证数据返回的唯一性
    district.search(adcode, function (status, result) {
        if (status === 'complete') {
            getData(result.districtList[0], obj.id);
        }
    });
}

function setCenter(obj) {
    map.setCenter(obj[obj.options.selectedIndex].center)
}

function initPage(DistrictCluster, PointSimplifier, $) {
    var pointSimplifierIns = new PointSimplifier({
        map: map, //所属的地图实例
        zIndex: 110,
        autoSetFitView: false, //禁止自动更新地图视野
        getPosition: function (item) {

            return item.position;
        },
        getHoverTitle: function (dataItem, idx) {
            return idx + ': ' + dataItem.dataItem;
        },
        renderOptions: {
            //点的样式
            pointStyle: {
                width: 6,
                height: 6,
                fillStyle: 'rgba(153, 0, 153, 0.38)'
            },
            //鼠标hover时的title信息
            hoverTitleStyle: {
                position: 'top'
            }
        }
    });
    var distCluster = new DistrictCluster({
        zIndex: 100,
        map: map, //所属的地图实例
        getPosition: function (item) {
            if (!item) {
                return null;
            }
            var parts = item.split(',');
            //返回经纬度
            return [parseFloat(parts[0]), parseFloat(parts[1])];
        },
        setData: function(points) {
            return points;
        },
        renderOptions: {
            //基础样式
            featureStyle: {
                fillStyle: '', //填充色
                lineWidth: 2, //描边线宽
                strokeStyle: 'rgb(31, 119, 180)', //描边色
                //鼠标Hover后的样式
                hoverOptions: {
                    fillStyle: 'rgba(255,242,0,0.8)'
                }
            },
            //特定区划级别的默认样式
            featureStyleByLevel: {
                //全国
                country: {
                    fillStyle: 'rgba(235, 248, 239, 0)'
                },
                //省
                province: {
                    fillStyle: 'rgba(116, 196, 118, 0.7)'
                },
                //市
                city: {
                    fillStyle: 'rgba(161, 217, 155, 0.6)'
                },
                //区县
                district: {
                    fillStyle: 'rgba(199, 233, 192, 0.5)'
                }
            }
        }
    });

    var currentAdcode = null;
    //监听区划面的点击
    distCluster.on('featureClick', function (e, feature) {
        currentAdcode = feature.properties.adcode;
        //获取该节点的聚合信息
        distCluster.getClusterRecord(currentAdcode, function (error, result) {
            //currentAdcode已经更新，有新的点击
            if (result.adcode !== currentAdcode) {
                return;
            }
            //设置数据
            pointSimplifierIns.setData(result.dataItems);
        })
    });

    // 点击聚合图标
    distCluster.on('clusterMarkerClick', function(e, record) {
    });

    distCluster.on('renderFinish', function (e, result) {
        var features = result.features;
        var currentAdcodeExists = false;
        for (var i = 0, len = features.length; i < len; i++) {
            if (currentAdcode === features[i].properties.adcode) {
                currentAdcodeExists = true;
                break;
            }
        }

        if (!currentAdcodeExists) {
            //如果当前adcode没有绘制，清除？
            //pointSimplifierIns.setData(null);
        }
    });


    window.distCluster = distCluster;

    function refresh() {
        var zoom = map.getZoom();
        //获取 pointStyle
        var pointStyle = pointSimplifierIns.getRenderOptions().pointStyle;
        //根据当前zoom调整点的尺寸
        pointStyle.width = pointStyle.height = 2 * Math.pow(1.2, map.getZoom() - 3);
    }

    map.on('zoomend', function () {
        refresh();
    });

    refresh();

    loading()
}

function loading() {
    $('<div id="loadingTip">数据加载中，请稍候......</div>').appendTo(document.body);
    $.ajax({
        url: '/loading/point',
        data:{},
        success: function(rsp) {
            if(console) {
                console.log('数据加载完成，共' + rsp.length + '条数据');
            }
            distCluster.setData(rsp);
            $('#loadingTip').remove();
        },
        error: function(error) {
            $('#loadingTip').remove();
        }
    });
}

function refreshCache() {
    $('<div id="loadingTip">缓存刷新中，请稍候......</div>').appendTo(document.body);
    $.ajax({
            url: '/cache/refresh',
            data:{},
            success: function(rsp) {
                if(console) {
                    console.log('缓存刷新完成，共' + rsp.length + '条数据');
                }
                distCluster.setData(rsp);
                $('#loadingTip').remove();
            },
            error: function(error) {
            }
        }
    );
}